package cn.com.generaldata.os.ws.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.helper.StringUtil;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Streams;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.generaldata.jsme_indicator_system.entity.UnitNz;
import cn.com.generaldata.jsme_indicator_system.entity.UnitPic;
import cn.com.generaldata.jsme_indicator_system.entity.UnitPro;
import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.constant.ReportConstant;
import cn.com.generaldata.os.newpojo.ReportVersion;
import cn.com.generaldata.os.newpojo.SystemCodedic;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.Area;
import cn.com.generaldata.os.pojo.AreaPerform;
import cn.com.generaldata.os.pojo.LArea;
import cn.com.generaldata.os.pojo.Role;
import cn.com.generaldata.os.service.common.AreaService;
import cn.com.generaldata.os.service.common.IndustryService;
import cn.com.generaldata.os.service.common.LAreaService;
import cn.com.generaldata.os.service.common.RoleService;
import cn.com.generaldata.os.service.common.StatSystemService;
import cn.com.generaldata.os.service.common.UserService;
import cn.com.generaldata.os.service.impl.UnitService;
import cn.com.generaldata.os.service.intf.IndicatorServiceInterface;
import cn.com.generaldata.os.service.intf.ReportServiceInterface;
import cn.com.generaldata.os.vo.ReportTypeVO;
import cn.com.generaldata.os.vo.ResultVO;
import cn.com.generaldata.os.vo.UnitVO;
import cn.com.generaldata.os.vo.UserVO;
import cn.com.generaldata.os.vo.VersionVO;

import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;

import edu.emory.mathcs.backport.java.util.Arrays;

@InjectName
@Component
@IocBean
public class UnitWS {

	private static Logger logger = LoggerFactory.getLogger(UnitWS.class);

	@Autowired
	private UnitService unitService;

	@Autowired
	private ReportServiceInterface reportService;

	@Autowired
	private StatSystemService statSystemService;

	@Autowired
	private IndicatorServiceInterface indicatorService;

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private IndustryService industryService;

	@Autowired
	private AreaService areaService;

	private List<Integer> yearList;

	private List<cn.com.generaldata.os.vo.RoleVO> roleList;

	@Autowired
	private LAreaService lareaService;
	
	@PostConstruct
	public void init() {

		// 获取当前日期
		Calendar cal = Calendar.getInstance();
		int tyear = cal.get(Calendar.YEAR);

		yearList = new ArrayList<Integer>();
		for (int i = tyear; i >= 1997; i--) {
			yearList.add(i);
		}

		roleList = queryRoles();

	}

	public String findServerPath() {
		String classPath = this.getClass().getClassLoader().getResource("/").getPath();
		try {
			classPath = URLDecoder.decode(classPath, "gb2312");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String[] strPath = classPath.split("/");
		String path = "";
		for (int i = 0; i < strPath.length; i++) {
			if (i > 0 && i <= 3) {
				path = path + strPath[i] + "/";
			}
		}
		return path;
	}

	public String uploadPic(String unitId, byte[] content, String fileName, String fileType) {
		// 存图片信息
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}
		String serverPath = findServerPath();
		if (content != null) {
			File file = new File(serverPath + File.separator + properties.getProperty("picUploadPath").trim()
					+ fileName); // 路径是存文件的路径
			try {
				FileOutputStream stream = new FileOutputStream(file);

				stream.write(content);
				stream.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("上传文件出错", e);
			}
			String picInfo = unitService.uploadPic(unitId, properties.getProperty("picUploadPath").trim() + fileName);
		}
		return fileName + ":success";
	}

	/*
	 * 注释"@Param("Filedata ") List<TempFile>  tempFiles," 中的Filedata是客户端 <input
	 * type =" Filedata " name =" Filedata " id ="file" /> 中的name名
	 */
	@At("/unit/uploadPic/?")
	@AdaptBy(type = UploadAdaptor.class)
	public String uploadPic(String unitId, @Param("uploadFile") TempFile uploadFile, HttpServletRequest req,
			ServletContext context, HttpSession session) {

		// 存图片信息
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}
		String serverPath = findServerPath();
		String fileName = uploadFile.getMeta().getFileLocalName();

		moveFile(uploadFile.getFile(), serverPath + File.separator + properties.getProperty("picUploadPath").trim()
				+ fileName);
		String multi = unitService.uploadPic(unitId, properties.getProperty("picUploadPath").trim() + fileName);
		return multi;
	}

	/**
	 * 根据企业ID查看上传的企业图片
	 * */
	@At("/unit/queryUnitPic/?")
	@Ok("json")
	public List<UnitPic> queryUnitPic(String unitId) {
		return unitService.queryUnitPic(unitId);
	}

	/**
	 * 根据ID删除企业图片
	 * */
	@At("/unit/delUnitPic/?")
	@Ok("json")
	public String delUnitPic(String id) {
		return unitService.delUnitPic(id);
	}

	/**
	 * 下载企业图片
	 * */
	@At("/unit/showUnitPic/?")
	@Ok("void")
	public void showUnitPic(String id, HttpServletResponse response) {
		List<UnitPic> list = unitService.showUnitPic(id);

		String path = "";
		if (list != null && list.size() > 0) {
			UnitPic unitPic = list.get(0);
			path = unitPic.getPicPath();
		}
		// 存图片信息
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");

		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}
		String serverPath = findServerPath();
		String filePath = serverPath + File.separator + path;

		OutputStream out = null;

		try {
			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", path));

			InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			response.reset();
			out = response.getOutputStream();

			out.write(buffer);

			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			Streams.safeClose(out);
		}
	}

	@At("/unit/unitPicMgr/?")
	@Ok("jsp:/static/ocean/unit/importUnitPic")
	public void unitPicMgr(String unitId, HttpServletRequest req) {

		req.setAttribute("unitId", unitId);

	}

	// 导入单位信息
	@At("/unit/uploadFile")
	@POST
	@AdaptBy(type = UploadAdaptor.class)
	@Ok("jsp:/static/ocean/unit/uploadOk")
	public void importUnit(@Param("uploadFile") TempFile uploadFile, ServletContext context, HttpServletRequest request) {
		// 导入的报表信息
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}

		if (uploadFile == null) {

			request.setAttribute("msg", "请选择文件。");
			return;
		}

		String folderPath = properties.getProperty("fileUploadPath").trim();

		String timeStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String ext = uploadFile.getMeta().getFileExtension();
		String newFileName = timeStr + ext;
		moveFile(uploadFile.getFile(), folderPath + newFileName);

		unitService.importEnterprise(new File(folderPath + newFileName));

		request.setAttribute("msg", "导入成功。");

	}
	
	// 导入企业
	@At("/unit/import")
	@POST
	@AdaptBy(type = UploadAdaptor.class)
	@Ok("jsp:/static/ocean/unit/uploadOk")
	public void imports(@Param("uploadFile") TempFile tempFile, HttpServletRequest request) {
		String msg = "";
		if (tempFile != null) {
			msg = unitService.importUnits(tempFile.getFile());
		}
		request.setAttribute("msg", ("errorTitle".equals(msg))?"模板错误。":"导入成功。");
	}

	private void saveFile(TempFile picFile, String folderPath) {

		String timeStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String fileName = picFile.getMeta().getFileLocalName();
		String ext = picFile.getMeta().getFileExtension();
		String newFileName = timeStr + ext;
		moveFile(picFile.getFile(), folderPath + newFileName);

	}

	private boolean moveFile(File source, String target) {

		if (source == null || target == null || "".equals(target)) {
			return false;
		}

		int dot = target.lastIndexOf("\\");
		String floder = target.substring(0, dot);
		File fl = new File(floder);
		if (!fl.exists()) {
			fl.mkdirs();
		}

		File f = new File(target);

		if (!f.exists()) {
			return source.renameTo(f);
		}

		return false;
	}

	// 导入企业信息

	public String importEnterprise(byte[] content, String fileName, String fileType) {
		// 导入的报表信息
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}

		String[] split = fileName.split(fileType);
		String saveFileName = split[0]; // 将用户上传的文件名进行按格式的修改，防止上传文件名重名而覆盖
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		saveFileName = String.valueOf(sdf.format(new Date())); // 登陆名后面加上传的日期
		// 日期后面加当前文件ID号、最大的序列号、文件的扩展名
		saveFileName += fileType; // 日期后面加最大的序列号、文件的扩展名

		if (content != null) {
			File file = new File(properties.getProperty("fileUploadPath").trim() + saveFileName); // 路径是存文件的路径
			try {
				FileOutputStream stream = new FileOutputStream(file);

				stream.write(content);
				stream.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("上传文件出错", e);
			}
			String importIndicator = unitService.importEnterprise(file);

			return importIndicator;
		}
		return null;
	}

	// 导入企业信息

	public String importUnitPro(byte[] content, String fileName, String fileType) {
		// 导入的报表信息
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}

		String[] split = fileName.split(fileType);
		String saveFileName = split[0]; // 将用户上传的文件名进行按格式的修改，防止上传文件名重名而覆盖
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		saveFileName = String.valueOf(sdf.format(new Date())); // 登陆名后面加上传的日期
		// 日期后面加当前文件ID号、最大的序列号、文件的扩展名
		saveFileName += fileType; // 日期后面加最大的序列号、文件的扩展名

		if (content != null) {
			File file = new File(properties.getProperty("fileUploadPath").trim() + saveFileName); // 路径是存文件的路径
			try {
				FileOutputStream stream = new FileOutputStream(file);

				stream.write(content);
				stream.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("上传文件出错", e);
			}
			String importIndicator = unitService.importUnitPro(file);

			return importIndicator;
		}
		return null;
	}

	/**
	 * 添加单位
	 * unit 企业信息
	 */
	@At("/role/createUnit")
	@Ok("jsp:/static/admin/unit/info")
	public void createUnit(HttpServletRequest request, HttpSession session) {
		
		request.setAttribute("action", "create");
		
		//	Area areaTown = new Area();
		//	Area areaCity = new Area();
		//	Area areaProvince = new Area();
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String unitId = voUser.getUserUnitId();
		//得到自己掌控的海洋局单位列表
		List<UnitNz> plist = unitService.checkChildren(ReportConstant.OCEAN, unitId);
		request.setAttribute("unitList", plist);
		List<AreaPerform> provinceList = new ArrayList<AreaPerform>();
		List<Area> cityList = new ArrayList<Area>();
		List<Area> townList = new ArrayList<Area>();

		provinceList = areaService.getChildren("0", provinceList);
		//	cityList = areaService.getChildren(areaProvince.getId(), cityList);
		//	townList = areaService.getChildren(areaCity.getId(), townList);
		request.setAttribute("provinceList", provinceList);
		request.setAttribute("cityList", cityList);
		request.setAttribute("townList", townList);

		request.setAttribute("roleList", roleList);
		
		request.setAttribute("zclxList", Arrays.asList(cn.com.generaldata.jsme_indicator_system.util.Constants.ZCLX.split(",")));

		List<cn.com.generaldata.os.vo.IndustryVO> industryList = queryIndustries();
		request.setAttribute("industryList", industryList);

	}

	@At("/role/addUnit")
	@Ok("jsp:/static/admin/unit/uploadOk")
	public void addUnit(@Param("..") UnitVO unit, HttpServletRequest request) throws Exception {
		String uid = unitService.createUnit(toPojo(unit));
		if (uid != null) {
			unitService.addUnitRelation(uid, unit.getPid());
			request.setAttribute("msg", "增加单位成功。");
		} else
			request.setAttribute("msg", "增加单位失败。");
	}

	/**
	 * 查找单位
	 * unitName 企业名称
	 * roleId 企业类型
	 */
	@At("/unit/select")
	@Ok("jsp:/static/admin/user/information/find")
	public ResultVO<UnitVO> queryUnit(HttpServletRequest request, @Param("unitName") String unitName,
			@Param("p") int pageNum) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("unitName");

		if (StringUtils.isNotBlank(unitName)) {
			filter.addRule(new FilterRule(FilterConstant.LIKE, "unitName", "%" + unitName.trim() + "%"));
		}

		Page page = null;
		if (pageNum != 0) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(unitService.queryUnits(filter, page));
	}

	public ResultVO<UnitVO> queryUnits(String unitName, String roleId, String createYear, Integer pageNum) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("unitName");

		// if (StringUtils.isNotBlank(loginName)) {
		// filter.addRule(new FilterRule(FilterConstant.LIKE, "userLoginname", "%" + loginName.trim() + "%"));
		// }

		if (StringUtils.isNotBlank(unitName)) {
			filter.addRule(new FilterRule(FilterConstant.LIKE, "unitName", "%" + unitName.trim() + "%"));
		}

		if (StringUtils.isNotBlank(roleId)) {
			String unitPro = "";
			// 涉海企业用户
			if (ReportConstant.SHEHAI_UNIT.equals(roleId)) {
				roleId = "3";
				unitPro = "1";
				filter.addRule(new FilterRule(FilterConstant.LIKE, "unitProper", "%" + unitPro + "%"));

			}
			// 用海企业用户
			else if (ReportConstant.YONGHAI_UNIT.equals(roleId)) {
				unitPro = "2";
				filter.addRule(new FilterRule(FilterConstant.LIKE, "unitProper", "%" + unitPro + "%"));

			}
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "role.id", roleId.trim()));

		}
		if (StringUtils.isNotBlank(createYear)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "createYear", createYear.trim()));
		}
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(unitService.queryUnits(filter, page));
	}

	public List<cn.com.generaldata.os.vo.RoleVO> queryRoles() {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("roleName");

		filter.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "roleDesc", "Root"));

		//获取单位性质
		cn.com.generaldata.os.vo.RoleVO r = new cn.com.generaldata.os.vo.RoleVO();
		r.setId("2");
		r.setRoleName("涉海企业用户");

		List<cn.com.generaldata.os.vo.RoleVO> list = toVoList(roleService.queryRoles(filter, null));
		list.add(r);

		return list;
	}

	private List<cn.com.generaldata.os.vo.RoleVO> toVoList(cn.com.generaldata.os.paging.Result pResult) {
		List<cn.com.generaldata.os.vo.RoleVO> roles = new ArrayList<cn.com.generaldata.os.vo.RoleVO>();
		for (cn.com.generaldata.os.pojo.Role pRole : (List<cn.com.generaldata.os.pojo.Role>) pResult
				.getOperationResult()) {
			roles.add(toVo(pRole));
		}
		return roles;
	}

	private cn.com.generaldata.os.vo.RoleVO toVo(cn.com.generaldata.os.pojo.Role pRole) {
		if (pRole != null) {
			return new cn.com.generaldata.os.vo.RoleVO(pRole.getId(), pRole.getRoleName(), pRole.getRoleDesc());
		}
		return null;
	}

	public List<cn.com.generaldata.os.vo.IndustryVO> queryIndustries() {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("dl");

		filter.addRule(new FilterRule(FilterConstant.GET_NULL, "zl", null));
		filter.addRule(new FilterRule(FilterConstant.GET_NULL, "xl", null));

		return toVList(industryService.queryIndustries(filter, null));
	}

	private List<cn.com.generaldata.os.vo.IndustryVO> toVList(cn.com.generaldata.os.paging.Result pResult) {
		List<cn.com.generaldata.os.vo.IndustryVO> industry = new ArrayList<cn.com.generaldata.os.vo.IndustryVO>();
		for (cn.com.generaldata.os.pojo.Industry pIndustry : (List<cn.com.generaldata.os.pojo.Industry>) pResult
				.getOperationResult()) {
			industry.add(toVo(pIndustry));
		}
		return industry;
	}

	private cn.com.generaldata.os.vo.IndustryVO toVo(cn.com.generaldata.os.pojo.Industry pIndustry) {
		if (pIndustry != null) {
			return new cn.com.generaldata.os.vo.IndustryVO(pIndustry.getId(), pIndustry.getDustryName(),
					pIndustry.getDustryDesc(), pIndustry.getTypeId(), pIndustry.getDl(), pIndustry.getZl(),
					pIndustry.getXl(), pIndustry.getCode());
		}

		return null;
	}

	/**
	 * 查找单位
	 * unitName 企业名称
	 * roleId 企业类型
	 */
	@At("/unit/list")
	@Ok("jsp:/static/ocean/unit/list")
	public ResultVO<UnitVO> queryAreaUnits(@Param("unitName") String unitName, @Param("roleId") String roleId,
			@Param("createYear") String createYear, @Param("areaId") String areaId, @Param("p") Integer pageNum,
			@Param("unitNo") String unitNo, HttpServletRequest request) {

		//获得录入年份列表
		request.setAttribute("yearList", yearList);

		request.setAttribute("roleList", roleList);

		List<SystemCodedic> sysList = queryType();
		request.setAttribute("sysList", sysList);

		String hql = "from Unit as u where 1=1";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(areaId)) {
			List<Area> list = new ArrayList<Area>();
			List<Area> areaList = areaService.findChildren(areaId, list);
			List<String> areaIds = new ArrayList<String>();
			areaIds.add(areaId);
			for (Area area : areaList) {
				areaIds.add(area.getId());
			}
			hql += " and u.area.id in (:areaIds)";
			map.put("areaIds", areaIds.toArray());
		}

		if (StringUtils.isNotBlank(unitName)) {
			hql += " and u.unitName like:unitName";
			map.put("unitName", "%" + unitName.trim() + "%");
		}
		if (StringUtils.isNotBlank(unitNo)) {
			hql += " and u.superCompanyCode= :unitNo";
			map.put("unitNo", unitNo);
		}
		if (StringUtils.isNotBlank(roleId)) {
			hql += " and u.role.id=:roleId";
			String unitPro = "";
			// 涉海企业用户
			if (ReportConstant.SHEHAI_UNIT.equals(roleId)) {
				roleId = "3";
				unitPro = "1";
				hql += " and u.unitProper like :unitPro";
				map.put("unitPro", "%" + unitPro + "%");
			}
			// 用海企业用户
			else if (ReportConstant.YONGHAI_UNIT.equals(roleId)) {
				unitPro = "2";
				hql += " and u.unitProper like :unitPro";
				map.put("unitPro", "%" + unitPro + "%");
			}
			map.put("roleId", roleId.trim());
		}
		if (StringUtils.isNotBlank(createYear)) {
			hql += " and u.createYear=:createYear";
			map.put("createYear", createYear.trim());
		}
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(unitService.queryUnitsByhql(hql, map, page));
	}

	/**
	 * @function 删除单位
	 * @param ids
	 */
	@At("/role/deleteMany")
	@Ok("json")
	public String removeUnits(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		unitService.removeUnits(idArray);
		return "{id:0}";

	}

	/**
	 * @function 修改单位
	 * @param ids
	 */
	@At("/unit/modify")
	@Ok("jsp:/static/ocean/unit/ok")
	@Fail("jsp:/static/ocean/unit/fail")
	public UnitVO modifyUnit(@Param("..") UnitVO unit) throws Exception {
		//1.查询在TBL_UNIT_RELATION表里是否有该单位
		//		List<UnitRelationNz> urnList = unitService.queryUnitRelation(unit.getDl());
		//		if (urnList == null || urnList.size() < 1) {
		//			throw new Exception();
		//		}

		//修改
		cn.com.generaldata.os.pojo.Unit modifyUnit = unitService.modifyUnit(toPojo(unit));

		//2.修改
		unitService.modifyUnitRelation(unit.getId(), unit.getPid());

		return unitService.toVo(modifyUnit);
	}

	@At("/unit/view")
	@Ok("jsp:/static/admin/unit/info")
	public UnitVO queryUnitById(@Param("id") String id, HttpServletRequest request, HttpSession session) {
		
		
		UnitVO vo = editUnitById(id, request, session);

		request.setAttribute("action", "view");
		
		return vo;
	}
		
	public UnitVO queryUnitById(@Param("id") String id, HttpServletRequest request) {
		
		request.setAttribute("action", "view");
		
		Area areaTown = new Area();
		Area areaCity = new Area();
		Area areaProvince = new Area();

		Map<String, String> itemMap = new HashMap<String, String>();

		String flag;

		cn.com.generaldata.os.pojo.Unit unit = unitService.queryUnitById(id);
		//根据id来找对应的省市县
		String areaId = unit.getArea().getId();
		String pid = unit.getPid();
		if (!StringUtil.isBlank(pid)) {
			cn.com.generaldata.os.pojo.Unit punit = unitService.queryUnitById(pid);
			itemMap.put("pname", punit.getUnitName());
		}
		char str[] = areaId.toCharArray();

		if (str[4] != '0' || str[5] != '0') {//县

			//找对应省市县
			areaTown = areaService.queryAreaById(areaId);
			areaCity = areaService.queryAreaById(areaTown.getParentId());
			areaProvince = areaService.queryAreaById(areaCity.getParentId());

			flag = "1";

			itemMap.put("townName", areaTown.getAreaName());
			itemMap.put("cityName", areaCity.getAreaName());
			itemMap.put("provinceName", areaProvince.getAreaName());
			itemMap.put("flag", flag);
		} else if (str[3] != '0' || str[2] != '0') {
			areaCity = areaService.queryAreaById(areaId);
			areaProvince = areaService.queryAreaById(areaCity.getParentId());

			flag = "2";

			itemMap.put("cityName", areaCity.getAreaName());
			itemMap.put("provinceName", areaProvince.getAreaName());
			itemMap.put("flag", flag);
		} else if (str[0] != '0' || str[1] != '0') {

			areaProvince = areaService.queryAreaById(areaId);

			flag = "3";

			itemMap.put("provinceName", areaProvince.getAreaName());
			itemMap.put("flag", flag);
		}
		request.setAttribute("areaName", itemMap);

		return unitService.toVo(unit);
	}

	@At("/unit/edit")
	@Ok("jsp:/static/admin/unit/info")
	public UnitVO editUnitById(@Param("id") String id, HttpServletRequest request, HttpSession session) {
		
		request.setAttribute("action", "edit");
		
		//找到当前企业记录
		cn.com.generaldata.os.pojo.Unit unit = unitService.queryUnitById(id);

		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		String unitId = voUser.getUserUnitId();
		//得到自己掌控的海洋局单位列表
		List<UnitNz> plist = unitService.checkChildren(ReportConstant.OCEAN, unitId);
		request.setAttribute("unitList", plist);
		request.setAttribute("unit", unit);
		request.setAttribute("zclxList", Arrays.asList(cn.com.generaldata.jsme_indicator_system.util.Constants.ZCLX.split(",")));
		
		
		Area areaTown = new Area();
		Area areaCity = new Area();
		Area areaProvince = new Area();

		Map<String, String> itemMap = new HashMap<String, String>();

		List<AreaPerform> provinceList = new ArrayList<AreaPerform>();
		List<AreaPerform> cityList = new ArrayList<AreaPerform>();
		List<AreaPerform> townList = new ArrayList<AreaPerform>();

		String flag = "";//前台判断哪个是areaId

		if (unit.getArea() != null) {

			//根据id来找对应的省市县
			String areaId = unit.getArea().getId();

			char str[] = areaId.toCharArray();

			if (str[4] != '0' || str[5] != '0') {

				//找对应省市县
				areaTown = areaService.queryAreaById(areaId);
				areaCity = areaService.queryAreaById(areaTown.getParentId());
				areaProvince = areaService.queryAreaById(areaCity.getParentId());
				request.setAttribute("larealist", lareaService.getLAreaChildren(areaId));

				flag = "1";

				itemMap.put("townId", areaId);
				itemMap.put("cityId", areaCity.getId());
				itemMap.put("provinceId", areaProvince.getId());
				itemMap.put("flag", flag);
			} else if (str[3] != '0' || str[2] != '0') {
				areaCity = areaService.queryAreaById(areaId);
				areaProvince = areaService.queryAreaById(areaCity.getParentId());

				flag = "2";

				itemMap.put("townId", "0");
				itemMap.put("cityId", areaId);
				itemMap.put("provinceId", areaProvince.getId());
				itemMap.put("flag", flag);
			} else if (str[0] != '0' || str[1] != '0') {

				areaProvince = areaService.queryAreaById(areaId);

				flag = "3";

				itemMap.put("townId", "0");
				itemMap.put("cityId", "0");
				itemMap.put("provinceId", areaProvince.getId());
				itemMap.put("flag", flag);
			}

			provinceList = areaService.getChildren("0", provinceList);
			cityList = areaService.getChildren(areaProvince.getId(), cityList);
			townList = areaService.getChildren(areaCity.getId(), townList);

		} else {
			itemMap.put("townId", "");
			itemMap.put("cityId", "");
			itemMap.put("provinceId", "");
		}
		request.setAttribute("areaMap", itemMap);

		request.setAttribute("provinceList", provinceList);
		request.setAttribute("cityList", cityList);
		request.setAttribute("townList", townList);

		request.setAttribute("roleList", roleList);

		List<cn.com.generaldata.os.vo.IndustryVO> industryList = queryIndustries();
		request.setAttribute("industryList", industryList);

		return unitService.toVo(unit);
	}

	/**
	 * 取得下级区域列表（注册时调用）.
	 */
	@At("/unit/getChildArea")
	@Ok("json")
	@Filters
	public List<AreaPerform> getChildArea(@Param("pid") String pid) {
		List<AreaPerform> area = new ArrayList<AreaPerform>();
		return areaService.getChildren(pid, area);
	}
	
	/**
	 * 取得下级区域列表（注册时调用）.
	 */
	@At("/unit/getLAreaChildArea")
	@Ok("json")
	@Filters
	public List<LArea> getLAreaChildArea(@Param("pid") String pid) {
		return lareaService.getLAreaChildren(pid);
	}

	@At("/unit/getReps")
	@Ok("json")
	@Filters
	public List<ReportTypeVO> queryRepsByStAndYear(@Param("year") String year, @Param("typeId") String typeId) {
		VersionVO vs = queryVersionByYear(year, typeId);
		if (vs != null) {
			List<ReportTypeVO> list = this.queryReportTypesByParam(String.valueOf(vs.getId()), typeId);
			return list;
		} else {
			return null;
		}

	}

	// 按年份查询版本

	public VersionVO queryVersionByYear(String year, String type) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("versionNumber");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		try {
			filter.addRule(new FilterRule(FilterConstant.LE, "startDate", sdf.parse(year)));
			filter.addRule(new FilterRule(FilterConstant.GE, "endDate", sdf.parse(year)));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (type == null) {
			type = "1";
		}
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "statSystem", Integer.valueOf(type)));
		cn.com.generaldata.os.paging.Result reportVersion = reportService.queryReportVersion(filter, null);
		if (reportVersion != null && reportVersion.getTotalCount() > 0) {
			List<ReportVersion> operationResult = (List<ReportVersion>) reportVersion.getOperationResult();
			ReportVersion version = operationResult.get(0);
			return toVoVersion(version);
		}
		return null;
	}

	private VersionVO toVoVersion(ReportVersion pVersion) {
		if (pVersion != null) {
			return new VersionVO(pVersion.getId().toString(), pVersion.getVersionNumber(), pVersion.getVersionName(),
					pVersion.getCreateTime(), pVersion.getStatSystem());
		}
		return null;
	}

	/**
	 * 获取企业的用海情况
	 * 
	 * @param unitId
	 * @return
	 */

	public List<UnitPro> findPros(String unitId) {
		return unitService.findPros(unitId);
	}

	@At("/unit/find")
	@Ok("jsp:/static/ocean/unit/find")
	public ResultVO<UserVO> findUnit(@Param("unitName") String unitName, @Param("roleId") String roleId,
			@Param("p") Integer pageNum, @Param("unitNo") String unitNo, @Param("reportId") String reportId,
			HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {

		// 准备查询参数
		cn.com.generaldata.os.vo.UserVO voUser = (cn.com.generaldata.os.vo.UserVO) session.getAttribute("user");
		request.setAttribute("reportId", reportId);
		request.setAttribute("roleList", roleList);
		if (ReportConstant.OCEAN.equals(voUser.getRoleId())) {
			String unitId = voUser.getUserUnitId();

			String hql = "from Unit as u where 1=1";
			HashMap map = new HashMap();
			if (StringUtils.isNotBlank(unitId)) {
				hql += " and exists (select a.id from UnitRelation as a where a.cid=u.id and a.depth=1 and a.pid=:unitId)";
				map.put("unitId", unitId);
			}

			if (StringUtils.isNotBlank(unitName)) {
				hql += " and u.unitName like:unitName";
				map.put("unitName", "%" + unitName.trim() + "%");
			}
			if (StringUtils.isNotBlank(unitNo)) {
				hql += " and u.superCompanyCode= :unitNo";
				map.put("unitNo", unitNo);
			}
			if (StringUtils.isNotBlank(roleId)) {
				hql += " and u.role.id=:roleId";
				String unitPro = "";
				// 涉海企业用户
				if (ReportConstant.SHEHAI_UNIT.equals(roleId)) {
					roleId = "3";
					unitPro = "1";
					hql += " and u.unitProper like :unitPro";
					map.put("unitPro", "%" + unitPro + "%");
				}
				// 用海企业用户
				else if (ReportConstant.YONGHAI_UNIT.equals(roleId)) {
					unitPro = "2";
					hql += " and u.unitProper like :unitPro";
					map.put("unitPro", "%" + unitPro + "%");
				}
				map.put("roleId", roleId.trim());
			}

			Page page = null;
			if (pageNum != null) {
				page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
			} else {
				page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
			}
			cn.com.generaldata.os.paging.Result unitsByhql = unitService.queryUnitsByhql(hql, map, page);
			List<cn.com.generaldata.os.pojo.Unit> unitList = (List<cn.com.generaldata.os.pojo.Unit>) unitsByhql
					.getOperationResult();
			List<cn.com.generaldata.os.pojo.User> userList = new ArrayList<cn.com.generaldata.os.pojo.User>();
			for (cn.com.generaldata.os.pojo.Unit unit : unitList) {
				String userHql = "from User us where userUnit.id= :unitId";
				map.put("unitId", unit.getId());
				cn.com.generaldata.os.paging.Result queryUsersByHql = userService.queryUsersByHql(userHql, map, null);
				if (queryUsersByHql.getOperationResult().size()>0){
					cn.com.generaldata.os.pojo.User user = (cn.com.generaldata.os.pojo.User) queryUsersByHql
							.getOperationResult().get(0);
					userList.add(user);
				}
			}
			unitsByhql.setOperationResult(userList);
			return userService.toVoResult(unitsByhql);
		}
		return new cn.com.generaldata.os.vo.ResultVO<cn.com.generaldata.os.vo.UserVO>();
	}

	@At("/unit/downloadTemple")
	@Ok("void")
	public void enterpriseTemple(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String encodedfileName = new String("企业导入模板.xls".getBytes(), "ISO8859-1");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		try {
			indicatorService.downEnterpriseTemple(out);
			out.flush();
		} finally {
			Streams.safeClose(out);
		}
	}

	//导入用海企业信息
	@At("/unit/uploadInfo")
	@POST
	@AdaptBy(type = UploadAdaptor.class)
	@Ok("jsp:/static/ocean/unit/uploadOk")
	public void importUnitInfo(@Param("uploadInfo") TempFile uploadInfo, ServletContext context,
			HttpServletRequest request, HttpServletResponse response, @Param("reportTypeId") String typeId,
			@Param("year") String year) {

		//	String fileName = uploadFile.getFile().getName();
		//	String fileType = uploadFile.getMeta().getFileExtension();

		// 导入的报表信息
		/*Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		OutputStream out = response.getOutputStream();
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}*/

		//	String[] split = fileName.split(fileType);
		//	String saveFileName = split[0]; // 将用户上传的文件名进行按格式的修改，防止上传文件名重名而覆盖
		//	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		//	saveFileName = String.valueOf(sdf.format(new Date())); // 登陆名后面加上传的日期
		// 日期后面加当前文件ID号、最大的序列号、文件的扩展名
		//	saveFileName += fileType; // 日期后面加最大的序列号、文件的扩展名

		if (uploadInfo == null) {

			request.setAttribute("msg", "请选择文件。");
			return;
		}

		File file = uploadInfo.getFile();
		/*try {
			FileOutputStream stream = new FileOutputStream(file);

			stream.write(content);
			stream.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("上传文件出错", e);
		}*/
		reportService.importUnitInfo(file, typeId, year);
		request.setAttribute("msg", "导入企业信息成功。");

	}

	@SuppressWarnings("unchecked")
	public List<ReportTypeVO> queryReportTypesByParam(String version, String type) {
		String hql = "from ReportType as rt where rt.versionId=:version and statSystem=:statSystem order by rt.statSystem,rt.sortNo,rt.subSortNo";
		HashMap map = new HashMap();
		map.put("version", Integer.valueOf(version));
		map.put("statSystem", Integer.valueOf(type));
		cn.com.generaldata.os.paging.Result hqlParam = reportService.queryReportTypeByHql(hql, map, null);
		return toVoListReportType(hqlParam);
	}

	private List<ReportTypeVO> toVoListReportType(cn.com.generaldata.os.paging.Result pResult) {
		List<ReportTypeVO> reportTypes = new ArrayList<ReportTypeVO>();
		List<SystemCodedic> queryType = queryType();
		for (cn.com.generaldata.os.newpojo.ReportType pReportType : (List<cn.com.generaldata.os.newpojo.ReportType>) pResult
				.getOperationResult()) {
			ReportTypeVO voReportType = toVoReportType(pReportType, queryType);
			if (voReportType != null) {
				reportTypes.add(voReportType);
			}
		}
		return reportTypes;
	}

	// 取得版本类型（三个）

	public List<SystemCodedic> queryType() {
		List<SystemCodedic> list = Lists.newArrayList();
		Map<String, String> statSystems = statSystemService.getStatSystemMap();
		for (Entry<String, String> entry : statSystems.entrySet()) {
			SystemCodedic sc = new SystemCodedic();
			sc.setCode(entry.getKey());
			sc.setCodeName(entry.getValue());
			list.add(sc);
		}
		return list;
	}

	private ReportTypeVO toVoReportType(cn.com.generaldata.os.newpojo.ReportType pReportType,
			List<SystemCodedic> queryType) {
		if (pReportType != null) {
			String type = "";
			for (SystemCodedic sc : queryType) {
				if (sc.getCode().equals(pReportType.getStatSystem().toString())) {
					type = sc.getCodeName();
					break;
				}
			}
			String name = pReportType.getTypeName();
			if (pReportType.getTypeNo() != null) {
				name = pReportType.getTypeNo() + "-" + pReportType.getTypeName();
			}
			return new ReportTypeVO(pReportType.getId(), name, pReportType.getTypeNo(), pReportType.getStatSystem()
					.toString(), pReportType.getTypeReportAdmin().toString(), pReportType.getTypeApproveAdmin()
					.toString(), pReportType.getTypeApproveNo(), pReportType.getTypeExpireDate(),
					pReportType.getTypeMeasureUnit(), pReportType.getTypeLastTime() == null ? 0 : pReportType
							.getTypeLastTime().shortValue(), pReportType.getTypeYearTime(), pReportType.getTypeTime(),
					type, pReportType.getVersionId().toString(), pReportType.getId());
		}
		return null;
	}

	public ResultVO<UnitVO> queryUnitByIds(String ids, Integer pageNum) {

		if (StringUtils.isNotBlank(ids)) {
			Filter filter = new Filter();
			filter.setOrder(FilterConstant.ASC);
			filter.setSortBy("unitName");
			// Result<Unit> result = new Result<Unit>();
			String[] split = ids.split(",");
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", split));
			Page page = null;
			if (pageNum != null) {
				page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
			}
			return toVoResult(unitService.queryUnits(filter, page));
		}
		return null;
	}

	public List<UnitVO> queryAllUsersByIndustryId(String industryId, String areaId) {
		// if (StringUtils.isNotBlank(industryId)) {
		String hql = "from Unit as u where u.role.id='4'";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(areaId)) {
			hql += " and exists (select a.id from AreaPerform as a where a.id=u.area.id and a.areaCode is not null and a.parentId=:areaId)";
			map.put("areaId", areaId);
		}
		if (StringUtils.isNotBlank(industryId)) {
			hql += " and exists (select ui.id from UserIndustry as ui where exists(select us.id from User as us where us.id=ui.user.id and us.userUnit.id=u.id) and ui.industry.id=:industryId)";
			map.put("industryId", industryId);
		}
		return toVoResult(unitService.queryUnitsByhql(hql, map, null)).getOperationResult();
		// }
		// }
		// return new ArrayList<Unit>();
	}

	private cn.com.generaldata.os.pojo.Unit toPojo(UnitVO unit) {
		if (unit != null) {
			cn.com.generaldata.os.pojo.Unit userPO = unitService.queryUnitById(unit.getId());

			Role role = new Role();
			Area area = new Area();
			role.setId(unit.getRoleId());
			area.setId(unit.getAreaId());
			LArea lArea = null;
			if (StringUtils.isNotBlank(unit.getLareaId())) {
				lArea = new LArea();
				lArea.setId(unit.getLareaId());
			}

			if (userPO != null) {
				return new cn.com.generaldata.os.pojo.Unit(userPO.getId(), role, unit.getIndustryId(), area, lArea,
						unit.getUnitName(), unit.getUnitInstitutionName(), unit.getUnitInstitutionCode(),
						unit.getRegistAdd(), unit.getAddr(), userPO.getRegistArea(), userPO.getRegistLArea(),
						unit.getQh(), unit.getTel(), unit.getFax(), unit.getMobile(), unit.getZclx(), unit.getLsgx(),
						unit.getDl(), unit.getZl(), unit.getXl(), unit.getLm(), unit.getYyzt(), unit.getProduct1(),
						unit.getProduct2(), unit.getProduct3(), unit.getKgqk(), unit.getPractitioner(), unit.getQyjt(),
						unit.getSuperCompanyCode(), unit.getFr(), unit.getUnitProper(), userPO.getCreateYear(), null,
						unit.getProInfo(), unit.getKkx(), unit.getKky(), unit.getKkz(), unit.getDlx(), unit.getDly(),
						unit.getDlz(), unit.getPid(), userPO.getStatus());
			} else
				return new cn.com.generaldata.os.pojo.Unit(unit.getId(), role, unit.getIndustryId(), area, lArea,
						unit.getUnitName(), unit.getUnitInstitutionName(), unit.getUnitInstitutionCode(),
						unit.getRegistAdd(), unit.getAddr(), area, lArea, unit.getQh(), unit.getTel(), unit.getFax(),
						unit.getMobile(), unit.getZclx(), unit.getLsgx(), unit.getDl(), unit.getZl(), unit.getXl(),
						unit.getLm(), unit.getYyzt(), unit.getProduct1(), unit.getProduct2(), unit.getProduct3(),
						unit.getKgqk(), unit.getPractitioner(), unit.getQyjt(), unit.getSuperCompanyCode(),
						unit.getFr(), unit.getUnitProper(), unit.getCreateYear() == null ? String.valueOf(new Date()
								.getYear()) : unit.getCreateYear(), null, unit.getProInfo(), unit.getKkx(),
						unit.getKky(), unit.getKkz(), unit.getDlx(), unit.getDly(), unit.getDlz(), unit.getPid(), "1");
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public ResultVO<UnitVO> toVoResult(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<UnitVO> result = new ResultVO<UnitVO>();

		List<UnitVO> units = new ArrayList<UnitVO>();
		for (cn.com.generaldata.os.pojo.Unit pUnit : (List<cn.com.generaldata.os.pojo.Unit>) pResult
				.getOperationResult()) {
			units.add(unitService.toVo(pUnit));
		}
		result.setOperationResult(units);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	//导出企业信息
	@At("/unit/downloadInfo")
	@Ok("void")
	public void generalExcelForQuery(@Param("unitName") String unitName, @Param("roleId") String roleId,
			@Param("createYear") String createYear, @Param("areaId") String areaId, @Param("unitNo") String unitNo,
			HttpServletRequest request, HttpServletResponse response) {
		ResultVO<UnitVO> units = queryAreaUnits(unitName, roleId, createYear, areaId, null, unitNo);
		List<UnitVO> result = units.getOperationResult();
		if (result != null && result.size() > 0) {
			List<String> ids = new ArrayList<String>();
			for (UnitVO unit : result) {
				ids.add(unit.getId());
			}

			String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String encodedfileName = dateStr + ".xls";
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
			try {
				OutputStream out = response.getOutputStream();
				unitService.generalExcel(ids, out);
				out.flush();
			} catch (IOException e) {

			}

		}

	}

	/**
	 * 查找单位
	 * unitName 企业名称
	 * roleId 企业类型
	 */

	public ResultVO<UnitVO> queryAreaUnits(String unitName, String roleId, String createYear, String areaId,
			Integer pageNum, String unitNo) {
		String hql = "from Unit as u where 1=1";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(areaId)) {
			List<Area> list = new ArrayList<Area>();
			List<Area> areaList = areaService.findChildren(areaId, list);
			List<String> areaIds = new ArrayList<String>();
			areaIds.add(areaId);
			for (Area area : areaList) {
				areaIds.add(area.getId());
			}
			hql += " and u.area.id in (:areaIds)";
			map.put("areaIds", areaIds.toArray());
		}

		if (StringUtils.isNotBlank(unitName)) {
			hql += " and u.unitName like:unitName";
			map.put("unitName", "%" + unitName.trim() + "%");
		}
		if (StringUtils.isNotBlank(unitNo)) {
			hql += " and u.superCompanyCode= :unitNo)";
			map.put("unitNo", unitNo);
		}
		if (StringUtils.isNotBlank(roleId)) {
			hql += " and u.role.id=:roleId";
			String unitPro = "";
			// 涉海企业用户
			if (ReportConstant.SHEHAI_UNIT.equals(roleId)) {
				roleId = "3";
				unitPro = "1";
				hql += " and u.unitProper like :unitPro";
				map.put("unitPro", "%" + unitPro + "%");
			}
			// 用海企业用户
			else if (ReportConstant.YONGHAI_UNIT.equals(roleId)) {
				unitPro = "2";
				hql += " and u.unitProper like :unitPro";
				map.put("unitPro", "%" + unitPro + "%");
			}
			map.put("roleId", roleId.trim());
		}
		if (StringUtils.isNotBlank(createYear)) {
			hql += " and u.createYear=:createYear";
			map.put("createYear", createYear.trim());
		}
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(unitService.queryUnitsByhql(hql, map, page));
	}

}
